const express = require('express');
const router = express.Router();
const pool = require('./db');

// 获取无法提交的练习ID
router.get('/api/get-unsubmittable-practices', async (req, res) => {
    try {
        const userId = req.query.userId;
        const [commitedPractices] = await pool.execute('SELECT practice_id FROM commited_practice WHERE commit_user_id = ? AND remaining_submit_times = 0', [userId]);
        const practiceIds = commitedPractices.map(practice => practice.practice_id);

        const [practices] = await pool.execute('SELECT practice_id, deadline FROM practice');
        const now = new Date();
        for (const practice of practices) {
            const deadline = new Date(practice.deadline);
            if (now > deadline) {
                const [commited] = await pool.execute('SELECT * FROM commited_practice WHERE practice_id = ? AND commit_user_id = ?', [practice.practice_id, userId]);
                if (commited.length > 0) {
                    practiceIds.push(practice.practice_id);
                }
            }
        }

        const uniquePracticeIds = [...new Set(practiceIds)];
        res.json(uniquePracticeIds);
    } catch (error) {
        console.error('获取无法提交的练习ID失败:', error);
        res.status(500).json({ error: '获取无法提交的练习ID失败' });
    }
});

// 获取错题信息
router.post('/api/get-incorrect-questions', async (req, res) => {
    try {
        const { practiceId, userId } = req.body;

        // 处理选择题
        const [choiceQuestions] = await pool.execute('SELECT question_order, correct_answer FROM choice_questions WHERE practice_id = ?', [practiceId]);
        for (const question of choiceQuestions) {
            const [commitedChoice] = await pool.execute('SELECT commited_answer FROM commited_choice_question WHERE practice_id = ? AND question_order = ? AND commit_user_id = ?', [practiceId, question.question_order, userId]);
            if (commitedChoice.length > 0 && commitedChoice[0].commited_answer !== question.correct_answer) {
                const [existing] = await pool.execute('SELECT * FROM incorrect_question WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                if (existing.length > 0) {
                    await pool.execute('UPDATE incorrect_question SET max_correct_times = 3 WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                } else {
                    await pool.execute('INSERT INTO incorrect_question (practice_id, user_id, question_order, max_correct_times) VALUES (?, ?, ?, 3)', [practiceId, userId, question.question_order]);
                }
            }
        }

        // 处理填空题
        const [fillQuestions] = await pool.execute('SELECT id, question_order, blank1_answer, blank2_answer, blank3_answer FROM fill_questions WHERE practice_id = ?', [practiceId]);
        for (const question of fillQuestions) {
            const [commitedFill] = await pool.execute('SELECT commited_answer1, commited_answer2, commited_answer3 FROM commited_fill_question WHERE practice_id = ? AND question_order = ? AND commit_user_id = ?', [practiceId, question.question_order, userId]);
            if (commitedFill.length > 0) {
                const blanks = [
                    { correct: question.blank1_answer, user: commitedFill[0].commited_answer1 },
                    { correct: question.blank2_answer, user: commitedFill[0].commited_answer2 },
                    { correct: question.blank3_answer, user: commitedFill[0].commited_answer3 }
                ];
                const isIncorrect = blanks.some(blank => blank.correct && blank.user !== blank.correct);
                if (isIncorrect) {
                    const [existing] = await pool.execute('SELECT * FROM incorrect_question WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                    if (existing.length > 0) {
                        await pool.execute('UPDATE incorrect_question SET max_correct_times = 3 WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                    } else {
                        await pool.execute('INSERT INTO incorrect_question (practice_id, user_id, question_order, max_correct_times) VALUES (?, ?, ?, 3)', [practiceId, userId, question.question_order]);
                    }
                }
            }
        }

        res.json({ message: '错题信息更新成功' });
    } catch (error) {
        console.error('获取错题信息失败:', error);
        res.status(500).json({ error: '获取错题信息失败' });
    }
});

// 获取所有错题详细信息
router.get('/api/get-all-incorrect-questions', async (req, res) => {
    try {
        const [incorrectQuestions] = await pool.execute('SELECT practice_id, user_id, question_order FROM incorrect_question');
        const choiceQuestions = [];
        const fillQuestions = [];

        for (const question of incorrectQuestions) {
            // 获取选择题信息
            const [choice] = await pool.execute('SELECT * FROM choice_questions WHERE practice_id = ? AND question_order = ?', [question.practice_id, question.question_order]);
            if (choice.length > 0) {
                choiceQuestions.push({ ...choice[0], type: 'choice' });
            }

            // 获取填空题信息
            const [fill] = await pool.execute('SELECT * FROM fill_questions WHERE practice_id = ? AND question_order = ?', [question.practice_id, question.question_order]);
            if (fill.length > 0) {
                fillQuestions.push({ ...fill[0], type: 'fill' });
            }
        }

        res.json({ choiceQuestions, fillQuestions });
    } catch (error) {
        console.error('获取所有错题详细信息失败:', error);
        res.status(500).json({ error: '获取所有错题详细信息失败' });
    }
});

// 获取错题信息（只插入数据版本）
router.post('/api/get-incorrect-questions-only-insert', async (req, res) => {
    try {
        const { practiceId, userId } = req.body;

        // 处理选择题
        const [choiceQuestions] = await pool.execute('SELECT question_order, correct_answer FROM choice_questions WHERE practice_id = ?', [practiceId]);
        for (const question of choiceQuestions) {
            const [commitedChoice] = await pool.execute('SELECT commited_answer FROM commited_choice_question WHERE practice_id = ? AND question_order = ? AND commit_user_id = ?', [practiceId, question.question_order, userId]);
            if (commitedChoice.length > 0 && commitedChoice[0].commited_answer !== question.correct_answer) {
                const [existing] = await pool.execute('SELECT * FROM incorrect_question WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                if (existing.length > 0) {
                    //await pool.execute('UPDATE incorrect_question SET max_correct_times = 3 WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                } else {
                    await pool.execute('INSERT INTO incorrect_question (practice_id, user_id, question_order, max_correct_times) VALUES (?, ?, ?, 3)', [practiceId, userId, question.question_order]);
                }
            }
        }

        // 处理填空题
        const [fillQuestions] = await pool.execute('SELECT id, question_order, blank1_answer, blank2_answer, blank3_answer FROM fill_questions WHERE practice_id = ?', [practiceId]);
        for (const question of fillQuestions) {
            const [commitedFill] = await pool.execute('SELECT commited_answer1, commited_answer2, commited_answer3 FROM commited_fill_question WHERE practice_id = ? AND question_order = ? AND commit_user_id = ?', [practiceId, question.question_order, userId]);
            if (commitedFill.length > 0) {
                const blanks = [
                    { correct: question.blank1_answer, user: commitedFill[0].commited_answer1 },
                    { correct: question.blank2_answer, user: commitedFill[0].commited_answer2 },
                    { correct: question.blank3_answer, user: commitedFill[0].commited_answer3 }
                ];
                const isIncorrect = blanks.some(blank => blank.correct && blank.user !== blank.correct);
                if (isIncorrect) {
                    const [existing] = await pool.execute('SELECT * FROM incorrect_question WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                    if (existing.length > 0) {
                        //await pool.execute('UPDATE incorrect_question SET max_correct_times = 3 WHERE practice_id = ? AND user_id = ? AND question_order = ?', [practiceId, userId, question.question_order]);
                    } else {
                        await pool.execute('INSERT INTO incorrect_question (practice_id, user_id, question_order, max_correct_times) VALUES (?, ?, ?, 3)', [practiceId, userId, question.question_order]);
                    }
                }
            }
        }

        res.json({ message: '错题信息更新成功' });
    } catch (error) {
        console.error('获取错题信息失败:', error);
        res.status(500).json({ error: '获取错题信息失败' });
    }
});

//获取题目最大尝试次数
router.get('/api/get-incorrect-question-attempts', async (req, res) => {
    try {
        const { practice_id, user_id, question_order } = req.query;
        
        // 查询错题表获取最大尝试次数
        const [results] = await pool.execute(
            'SELECT max_correct_times FROM incorrect_question WHERE practice_id = ? AND user_id = ? AND question_order = ?',
            [practice_id, user_id, question_order]
        );
        
        if (results.length > 0) {
            res.json({ 
                success: true,
                max_correct_times: results[0].max_correct_times
            });
        } else {
            // 如果题目不在错题表中，返回默认值或错误
            res.json({ 
                success: false,
                message: '未找到该错题记录',
                max_correct_times: 0
            });
        }
    } catch (error) {
        console.error('获取错题尝试次数失败:', error);
        res.status(500).json({ error: '服务器内部错误' });
    }
});

// 删除错题接口
router.post('/api/delete-incorrect-question', async (req, res) => {
    try {
        const { practice_id, user_id, question_order } = req.body;
        // 验证参数
        if (!practice_id || !user_id || isNaN(question_order)) {
            return res.status(400).json({ error: '缺少必要参数' });
        }
        // 执行删除操作
        
        const [result] = await pool.execute('DELETE FROM incorrect_question WHERE practice_id = ? AND user_id = ? AND question_order = ?',[practice_id, user_id, question_order]);  
        // 检查是否删除成功
        if (result.affectedRows > 0) {
            res.json({ success: true, message: '错题记录已删除' });
        } else {
            res.json({ success: false, message: '未找到对应的错题记录' });
        }
    } catch (error) {
        console.error('删除错题失败:', error);
        res.status(500).json({ error: '服务器内部错误' });
    }
});

router.post('/api/update-correct-times', async (req, res) => {
    try {
        const { practice_id, user_id, question_order } = req.body;
        // 更新正确次数的逻辑
        await pool.execute(
            'UPDATE incorrect_question SET max_correct_times = max_correct_times - 1 WHERE practice_id = ? AND user_id = ? AND question_order = ?',
            [practice_id, user_id, question_order]
        );
        
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '服务器错误' });
    }
});

router.get('/api/check-incorrect-question', async (req, res) => {
    try {
        // 从查询参数中获取练习ID、题目序号和用户ID
        const { practiceId, questionOrder, userId } = req.query;
        
        // 验证参数
        if (!practiceId || !questionOrder || !userId) {
            return res.status(400).json({ 
                success: false, 
                message: '缺少必要参数: practiceId, questionOrder 或 userId' 
            });
        }
        
        // 查询数据库检查错题是否存在
        const [results] = await pool.execute(
            'SELECT * FROM incorrect_question WHERE practice_id = ? AND question_order = ? AND user_id = ?',
            [practiceId, questionOrder, userId]
        );
        
        const [choiceResults] = await pool.execute('SELECT * FROM choice_questions WHERE practice_id = ? AND question_order = ? ',[practiceId, questionOrder]);

        // 返回检查结果
        res.json({
            success: true,
            type: choiceResults.length > 0 ? 'choice' : 'fill',
            exists: results.length > 0
        });
        
    } catch (error) {
        console.error('检查错题是否存在失败:', error);
        res.status(500).json({ 
            success: false, 
            message: '服务器内部错误',
            error: error.message 
        });
    }
});

module.exports = router;